<template>
  <div class="hotel-detail" v-if="hotel">
    <!-- 酒店头部信息 -->
    <div class="hotel-header">
      <h1>{{ hotel.name }}</h1>
      <div class="hotel-meta">
        <div class="rating">
          <el-rate v-model="hotel.overallRating" disabled show-score
            :score-template="`${hotel.overallRating.toFixed(1)}`" />
          <span class="review-count">{{ hotel.reviewCount }}条评价</span>
        </div>
        <div class="location">
          <el-icon>
            <Location />
          </el-icon>
          <span>{{ hotel.city }}, {{ hotel.state }}</span>
        </div>
      </div>
    </div>

    <!-- 图片画廊 -->
    <div class="gallery">
      <div class="main-image">
        <img :src="mainImage" :alt="hotel.name">
      </div>
      <div class="thumbnails">
        <div v-for="(image, index) in hotel.images" :key="index" class="thumbnail" @click="changeMainImage(image)">
          <img :src="image.imageUrl" :alt="`${hotel.name}-${index}`">
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧内容 -->
      <div class="left-content">
        <!-- 设施部分 -->
        <section class="facilities">
          <h2>酒店设施</h2>
          <div class="facility-grid">
            <div v-for="facility in hotel.facilities" :key="facility.id" class="facility-item">
              <el-icon>
                <Check />
              </el-icon>
              <span>{{ facility.name }}</span>
            </div>
          </div>
        </section>

        <!-- 房型部分 -->
        <section class="room-types">
          <h2>选择房型</h2>

          <!-- 日期选择器 -->
          <div class="date-picker">
            <el-form :model="searchForm" inline>
              <el-form-item label="入住日期">
                <el-date-picker v-model="searchForm.checkIn" type="date" placeholder="选择日期" :disabled-date="disabledCheckInDate"/>
              </el-form-item>
              <el-form-item label="离店日期">
                <el-date-picker v-model="searchForm.checkOut" type="date" placeholder="选择日期"
                  :disabled="!searchForm.checkIn" :disabled-date="disabledCheckOutDate" />
              </el-form-item>
              <el-form-item label="大人" style="width: 200px;">
                <el-select v-model="searchForm.adult" placeholder="选择人数">
                  <el-option v-for="n in [0,1,2,3,4]" :key="n" :label="`${n}人`" :value="n" />
                </el-select>
              </el-form-item>
              <el-form-item label="小孩" style="width: 200px;">
                <el-select v-model="searchForm.children" placeholder="选择人数">
                  <el-option v-for="n in [0,1,2,3,4]" :key="n" :label="`${n}人`" :value="n" />
                </el-select>
              </el-form-item>
            </el-form>
            <div class="price_total"> 
              <span style="margin: 0 0 30px 510px;">您一共预定了{{ totalNum }}间房间，总金额为{{ totalPrice }}元</span>
              <el-button type="primary" @click="bookRoom(room)" style="margin: 0 0 10px 80px;">预订</el-button>
            </div>
          </div>

          <!-- 房型列表 -->
          <div class="room-list">
            <div v-for="room in filteredRooms" :key="room.id" class="room-card">
              <div class="room-info">
                <h3>{{ room.name }}</h3>
                <p class="description">{{ room.description }}</p>
                <div class="features">
                  <el-tag v-for="(feature, index) in room.features" :key="index" size="small">
                    {{ feature }}
                  </el-tag>
                </div>
                <div class="details">
                  <p><el-icon>
                      <OfficeBuilding />
                    </el-icon> {{ room.roomSize }}㎡</p>
                  <p><el-icon>
                      <UserFilled />
                    </el-icon> {{ room.bedType }}</p>
                  <p><el-icon>
                      <User />
                    </el-icon> 最多{{ room.maxOccupancy }}人</p>
                </div>
                <div class="cancellation">
                  <el-tag v-if="room.freeCancellation" type="success" size="small">
                    免费取消
                  </el-tag>
                  <el-tag v-else type="danger" size="small">
                    不可取消
                  </el-tag>
                </div>
              </div>

              <div class="room-price">
                <div class="price">
                  <span class="current">¥{{ room.basePrice }}</span>
                  <span v-if="room.originalPrice" class="original">¥{{ room.originalPrice }}</span>
                </div>
                <el-input-number v-model="room.bookingNum" :min="0" :max="10" />
              </div>
            </div>
          </div>
        </section>

        <!-- 酒店描述 -->
        <section class="description">
          <h2>酒店介绍</h2>
          <p>{{ hotel.description }}</p>
        </section>
        <!-- 评论部分 -->
        <section class="reviews">
          <h2>住客点评 ({{ hotel.reviewCount }})</h2>
          <span class="rating">{{ hotel.overallRating }}</span>
        </section>
      </div>

      <!-- 右侧预订栏 -->
      <div class="right-sidebar">
        <div class="booking-card">
          <div class="price-summary">
            <div class="average-price">
              <span>均价</span>
              <span>¥{{ averagePrice }}</span>
            </div>
            <div class="selected-dates" v-if="searchForm.checkIn && searchForm.checkOut">
              <span>入住日期</span>
              <span>{{ formatDate(searchForm.checkIn) }}</span>
              <span>离店日期</span>
              <span>{{ formatDate(searchForm.checkOut) }}</span>
            </div>
          </div>

          <el-button type="primary" class="quick-book" @click="quickBook">
            快速预订
          </el-button>

          <div class="contact">
            <h3>联系酒店</h3>
            <p><el-icon>
                <Phone />
              </el-icon> 021-12345678</p>
            <p><el-icon>
                <Message />
              </el-icon> contact@hotel.com</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div v-else-if="loading" class="loading">
    <el-skeleton :rows="10" animated />
  </div>

  <div v-else class="error">
    <el-empty description="酒店信息加载失败" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import {
  Location, Check, OfficeBuilding,
  User, Phone, Message,UserFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { v4 as uuidv4 } from 'uuid';
const router = useRouter()

const route = useRoute()
const hotelId = route.params.id

// 酒店数据
const hotel = ref(null)
const loading = ref(true)
const error = ref(null)
const hotelReviews = ref([])
const hasSearched = ref(true)

// 搜索表单
const searchForm = ref({
  checkIn: new Date(),
  checkOut: new Date(Date.now() + 24 * 60 * 60 * 1000), // 当前时间 + 1天
  adult:1,
  children:1,
})

// 主图
const mainImage = computed(() => {
  if (!hotel.value?.images) return ''
  const primary = hotel.value.images.find(img => img.isPrimary)
  return primary?.imageUrl || hotel.value.images[0]?.imageUrl || ''
})

// 禁用离店日期（必须晚于入住日期）
const disabledCheckOutDate = (time) => {
  if (!searchForm.value.checkIn) return true
  return time.getTime() <= searchForm.value.checkIn.getTime()
}

// 禁用入住日期（只能选择今天及以后的日期）
const disabledCheckInDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const filteredRooms = computed(() => {
  if (!hasSearched.value) return []
  const { adult } = searchForm.value
  const { children } = searchForm.value
  
  if (!adult) return []
  
  return hotel.value.roomTypes.filter(room => {
    // 筛选条件：房间最大入住人数 >= 选择的人数
    return room.maxOccupancy >= adult + children
  })
})
// 获取酒店详情
const fetchHotelDetails = async () => {
  try {
    loading.value = true
    const response1 = await axios.get(`/api/hotels/${hotelId}`)
    const response2 = await axios.get(`/api/reviews/hotel/${hotelId}`)
    hotel.value = response1.data
    hotelReviews.value = response2.data
    console.log(hotel.value)
    console.log(hotelReviews.value)
  } catch (err) {
    error.value = err
    console.error('获取酒店详情失败:', err)
  } finally {
    loading.value = false
  }
}

// 计算平均价格
const averagePrice = computed(() => {
  if (!hotel.value?.roomTypes?.length) return 0
  const sum = hotel.value.roomTypes.reduce((sum, room) => sum + room.basePrice, 0)
  return Math.round(sum / hotel.value.roomTypes.length)
})

// 计算总价
const calculateTotal = (room) => {
  if (!searchForm.value.checkIn || !searchForm.value.checkOut) {
    return room.basePrice
  }

  const roomNum = computed(() => room.bookingNum)

  return room.basePrice * roomNum.value
}

const totalNum = computed(() => {
  return hotel.value.roomTypes.reduce((total, room) => total + room.bookingNum, 0)
})

const totalPrice = computed(() => {
  return hotel.value.roomTypes.reduce((total, room) => total + calculateTotal(room), 0)
})
// 切换主图
const changeMainImage = (image) => {
  // 在实际应用中，这里可以更新主图状态
  console.log('切换到图片:', image)
}

// 预订房间
const bookRoom = (room) => {
  if (!searchForm.value.checkIn || !searchForm.value.checkOut || searchForm.value.adult == 0) {
    ElMessage.warning('请输入正确的信息')
    return
  }

  // 获取所有预定数不为0的房间
  const selectedRooms = hotel.value.roomTypes.filter(room => room.bookingNum > 0)
  
  if (selectedRooms.length === 0) {
    ElMessage.warning('请至少选择一间房')
    return
  }

   const queryParams = {
    hotelId: hotel.value.id,
    hotelName: hotel.value.name,
    checkIn: searchForm.value.checkIn.toISOString(), // 转换为ISO字符串
    checkOut: searchForm.value.checkOut.toISOString(),
    totalPrice: totalPrice.value,
    totalNum: totalNum.value,
    selectedRooms: JSON.stringify(selectedRooms), // 将数组转为JSON字符串
    orderId: 123
  }
  console.log(queryParams)
  // 跳转到预订页面
  router.push({
    path: '/reservation', // 使用path而不是name更可靠
    query: queryParams
  })
}

// 快速预订
const quickBook = () => {
  if (!searchForm.value.checkIn || !searchForm.value.checkOut) {
    ElMessage.warning('请选择入住和离店日期')
    return
  }

  // 预订最便宜的房间
  const cheapestRoom = [...hotel.value.roomTypes].sort((a, b) => a.basePrice - b.basePrice)[0]
  bookRoom(cheapestRoom)
}

onMounted(() => {
  fetchHotelDetails()
})
// 评价分页
const currentPage = ref(1)
const pageSize = ref(5)

// 计算分页后的评价


// 计算总体评分
const overallRating = computed(() => {
  if (!hotelReviews.value.length) return hotel.value.overallRating || 0

  const sum = hotelReviews.value.reduce((sum, review) => sum + review.rating, 0)
  return sum / hotelReviews.value.length
})

// 评分文本描述
const ratingText = computed(() => {
  const rating = overallRating.value
  if (rating >= 4.5) return '非常好'
  if (rating >= 4.0) return '很好'
  if (rating >= 3.5) return '不错'
  if (rating >= 3.0) return '一般'
  return '较差'
})

// 获取特定星级的评价数量


// 获取星级百分比
const getRatingPercentage = (star) => {
  if (!hotelReviews.value.length) return 0
  return (getRatingCount(star) / hotelReviews.value.length) * 100
}

// 星级进度条颜色
const getRatingColor = (star) => {
  const colors = {
    5: '#00a680',
    4: '#5cb85c',
    3: '#f0ad4e',
    2: '#ff9900',
    1: '#d9534f'
  }
  return colors[star] || '#409eff'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 图片预览
const openImagePreview = (imgUrl) => {
  // 实际应用中可以使用Element Plus的图片预览组件
  console.log('预览图片:', imgUrl)
}

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  window.scrollTo({
    top: document.querySelector('.reviews').offsetTop - 20,
    behavior: 'smooth'
  })
}
</script>

<style scoped>
.hotel-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
  color: #333;
}

.hotel-header {
  margin-bottom: 30px;
}

.hotel-title {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.hotel-title h1 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #003580;
}

.hotel-rating {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.hotel-rating :deep(.el-rate) {
  display: inline-flex;
}

.review-count {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.hotel-location {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #666;
}

.hotel-location .el-icon {
  margin-right: 5px;
}

.hotel-location .el-link {
  margin-left: 15px;
}

/* 酒店图片展示 */
.hotel-gallery {
  display: flex;
  margin-bottom: 30px;
  height: 400px;
}

.main-image {
  flex: 2;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-container {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.thumbnail {
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  gap: 30px;
}

.left-content {
  flex: 2;
}

.right-sidebar {
  flex: 1;
}

/* 设施区域 */
.facilities-section {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.facilities-section h2 {
  font-size: 22px;
  margin-bottom: 15px;
  color: #003580;
}

.facilities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.facility-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.facility-item .el-icon {
  margin-right: 5px;
  color: #003580;
}

/* 房型选择 */
.room-types-section {
  margin-bottom: 30px;
}

.room-types-section h2 {
  font-size: 22px;
  margin-bottom: 15px;
  color: #003580;
}

.date-selector {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.date-selector .el-form-item {
  margin-bottom: 0;
}

/* 房型卡片 */
.room-card {
  display: flex;
  justify-content: space-between;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 15px;
}

.room-info {
  flex: 2;
}

.room-info h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #003580;
}

.room-features {
  margin-bottom: 10px;
}

.room-features .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.room-details {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.room-details p {
  margin: 0;
  display: flex;
  align-items: center;
}

.room-details .el-icon {
  margin-right: 5px;
}

.cancellation-policy {
  margin-top: 10px;
}

.non-refundable {
  color: #f56c6c;
  font-size: 14px;
}

.room-price {
  flex: 1;
  text-align: right;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.price-display {
  margin-bottom: 10px;
}

.current-price {
  font-size: 24px;
  font-weight: bold;
  color: #003580;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
  margin-left: 5px;
}

.tax-info {
  display: block;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.price-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

/* 酒店描述 */
.hotel-description {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.hotel-description h2 {
  font-size: 22px;
  margin-bottom: 15px;
  color: #003580;
}

.hotel-description p {
  line-height: 1.6;
}

/* 评论区域 */
.reviews-section h2 {
  font-size: 22px;
  margin-bottom: 15px;
  color: #003580;
}

.review-summary {
  display: flex;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.overall-rating {
  flex: 1;
  text-align: center;
}

.rating-score {
  display: block;
  font-size: 28px;
  font-weight: bold;
  color: #003580;
}

.rating-text {
  display: block;
  font-size: 16px;
  margin: 5px 0;
}

.review-count {
  font-size: 14px;
  color: #666;
}

.rating-bars {
  flex: 2;
}

.rating-bar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.rating-label {
  width: 40px;
  font-size: 14px;
}

.rating-bar :deep(.el-progress) {
  flex: 1;
  margin: 0 10px;
}

.rating-count {
  width: 30px;
  font-size: 14px;
  color: #666;
}

.review-list {
  margin-top: 20px;
}

.review-card {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.reviewer-info {
  display: flex;
  align-items: center;
}

.reviewer-name {
  font-weight: bold;
  margin-right: 10px;
}

.review-date {
  color: #666;
  font-size: 14px;
}

.review-content h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.review-content p {
  margin: 0;
  line-height: 1.6;
  color: #333;
}

/* 右侧预订侧边栏 */
.booking-card {
  position: sticky;
  top: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 20px;
  background-color: #f9f9f9;
}

.price-summary {
  margin-bottom: 20px;
}

.average-price,
.selected-dates {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.average-price .label,
.selected-dates .label {
  color: #666;
}

.average-price .value {
  font-size: 20px;
  font-weight: bold;
  color: #003580;
}

.selected-dates .value {
  font-weight: 500;
}

.quick-booking {
  margin-bottom: 20px;
}

.quick-booking .el-button {
  width: 100%;
}

.notice {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin-top: 10px;
}

.hotel-contacts h3 {
  font-size: 16px;
  margin-bottom: 10px;
  color: #003580;
}

.hotel-contacts p {
  display: flex;
  align-items: center;
  margin: 5px 0;
  font-size: 14px;
}

.hotel-contacts .el-icon {
  margin-right: 5px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .main-content {
    flex-direction: column;
  }

  .right-sidebar {
    order: -1;
    margin-bottom: 30px;
  }

  .booking-card {
    position: static;
  }
}

@media (max-width: 768px) {
  .hotel-gallery {
    flex-direction: column;
    height: auto;
  }

  .main-image {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .thumbnail-container {
    grid-template-columns: repeat(4, 1fr);
  }

  .room-card {
    flex-direction: column;
  }

  .room-price {
    margin-top: 15px;
    text-align: left;
  }

  .review-summary {
    flex-direction: column;
  }

  .overall-rating {
    margin-bottom: 15px;
  }

  /* 评论区域样式 */
  .reviews {
    margin-top: 40px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }

  .reviews h2 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #333;
  }

  .rating-summary {
    display: flex;
    margin-bottom: 30px;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
  }

  .overall {
    flex: 1;
    text-align: center;
    padding: 10px;
  }

  .overall .score {
    display: block;
    font-size: 36px;
    font-weight: bold;
    color: #003580;
    margin-bottom: 5px;
  }

  .overall .text {
    display: block;
    font-size: 16px;
    color: #666;
    margin-bottom: 10px;
  }

  .overall .stars {
    display: flex;
    justify-content: center;
  }

  .rating-bars {
    flex: 2;
    padding: 10px;
  }

  .bar {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }

  .bar .label {
    width: 50px;
    font-size: 14px;
    color: #666;
  }

  .bar :deep(.el-progress) {
    flex: 1;
    margin: 0 15px;
  }

  .bar .count {
    width: 40px;
    font-size: 14px;
    color: #666;
    text-align: right;
  }

  /* 评价列表 */
  .review-list {
    margin-top: 20px;
  }

  .review-card {
    padding: 20px 0;
    border-bottom: 1px solid #eee;
  }

  .review-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }

  .reviewer {
    display: flex;
    align-items: center;
  }

  .reviewer-info {
    margin-left: 10px;
  }

  .reviewer-info .name {
    display: block;
    font-weight: bold;
    margin-bottom: 3px;
  }

  .reviewer-info .stay-date {
    font-size: 12px;
    color: #999;
  }

  .review-rating {
    text-align: right;
  }

  .review-rating .rating-date {
    display: block;
    font-size: 12px;
    color: #999;
    margin-top: 3px;
  }

  .review-content h4 {
    margin: 0 0 10px 0;
    font-size: 16px;
    color: #333;
  }

  .review-content p {
    margin: 0 0 15px 0;
    line-height: 1.6;
    color: #666;
  }

  .review-images {
    display: flex;
    gap: 10px;
    margin-top: 10px;
  }

  .review-images img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 0.3s;
  }

  .review-images img:hover {
    transform: scale(1.05);
  }

  /* 分页样式 */
  .el-pagination {
    margin-top: 30px;
    justify-content: center;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .rating-summary {
      flex-direction: column;
    }

    .overall {
      margin-bottom: 20px;
    }

    .review-header {
      flex-direction: column;
    }

    .review-rating {
      margin-top: 10px;
      text-align: left;
    }
  }
}
</style>